<?php



class CP_Controller{
    
    //Metoden tar inn og behandler kommentarer. Den tolker bedrifter, produkter og rating med tilhørende identifikatorer @, # og %
    public function commentReceiver($comment="",$userid=0){
        // receives the comment with product,company and rating insde of $comment, we have to finde them.
        $company    =   "";
        $product    =   "";
        $pieces     =   "";
        $pieces1    =   "";
        $pieces2    =   "";
        $rate       =    0;
        
        //find company
        $pieces     =   explode("@",$comment);
        $pieces1    =   explode(" ",$pieces[1]);
        $company    =   $pieces1[0];
        
        //find product
        $pieces     = explode("#",$comment);
        $pieces2    = explode(" ",$pieces[1]);
        $product    = $pieces2[0];
        
        //find rating
        $pieces     = explode("%",$comment);
        $pieces3    = explode(" ",$pieces[1]);
        $rate       = $pieces3[0];
        
        // if no company and product
        if($company=="" && $product==""){
            return "Når du kommenter må du bruke @ foran Bedrift og/-eller # foran produkt</br>";
        
        // else all in order, save all the data. 
        }else{
           
            if(!($rate >=1 && $rate <=10) && $rate != '' ){
                return "Karakter må være mellom 1-10";
            }else{
                $c =self::commentHandle($comment,$company,$product,$rate,$userid);
                
                if(isset($c)){
                    //all is good redirect to the page where the product and company is

                    redirect_to("compro.php?id=".$c);
            }
            }
                
        
        }
        echo "Bedrift:  ".$company."</br> Product:  ".$product."</br> Karakter:  ".$rate."</br> Kommentar:  ".$comment; 
        
        
          
    }
    
    
    //Method returns a prepared feed from recent comments.
    public function commentFeed(){
        
        $co = new Comment();
        
        $recent = $co->getRecentComments();
        $res = $this->prepareFeed($recent);
        
        return $res;
    }
    
    //Method recieves a comment table and prepares the comment as presentable html
    private function prepareFeed($tab){
        $html = "<div id='feed'>";
        
        foreach($tab as $co){
            $user = User::find_by_id($co->user_id);
            $html .= "<div id ='comment'>";
            $html .= "<div id='user'><b>".$user->username."</b> shouts: </div>";
            $html .= "<div id='text'><a href=compro.php?id=".$co->connection_id.">".$this->prepareComment($co->comment)."</a></div>";
            $html .= "<div id='time'>".$co->timestamp."</div>";
            $html .= "</div>";
        }
        $html .= "</div>";
        
        return $html;
    }
    
    // Recieves a comment object and prepares it as string
    private function prepareComment($comment){
        
        $newcomment = str_replace("-", " ", $comment);
        $newcomment = str_replace("%", " - Rate: ", $comment);
        
        return $newcomment;
    }
    
    
    // Receives the comment from comment receiver and will handle all the information, and save it at the correct models. 
    private function commentHandle($commentc="",$companyc="",$productc="",$ratec=0,$userid=0){
       
        $company = new Company();
        $product = new Product();
        $comment = new Comment();
        $rate = new Rate();
        $company_product = new Company_Product();
        
        if($company->companyExists($companyc)){
            //company Excist, we find the id
            if(!$companyc==""){
            
           $companyid = $company->companyExists($companyc)->id;

           }else{
                //company is not mentioned in comment
               $companyid = 0;
            }
            
        }else{
            //company does not excist, we make new company
            
            $company->name = $companyc;
            $company->save();
            $companyid = $company->id;
            $company_product->company_id = $companyid;
            $company_product->prodcut_id = 0;
            $company_product->save();
        }
        if($product->productExists($productc)){
            // product Exist, we find the id
            if(!$productc == ""){
                   $productid = $product->productExists($productc)->id;
            }else{
                //product is not mentioned in comment
                $productid= 0;
                
            }
        }else{
            //product does not excist, we make new product
            
            $product->name= $productc;
            $product->user_id= $userid;
            $product->save();
            $productid = $product->id;
            $company_product->product_id = $productid;
            $company_product->company_id = 0;
            $company_product->save();
        }
        // make entry in connection_table
        if($company_product->isregistered($companyid, $productid)){
            // if connection entry excist 
            $company_productid = $company_product->isregistered($companyid, $productid)->id;
            
        }else{
        $company_product->company_id = $companyid;
        $company_product->product_id = $productid;
        //get connid
        $company_product->save();
        $company_productid = $company_product->id;
            
        }
        // add all variables and save to comment
        $comment->comment = $commentc;
        $comment->timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
        $comment->connection_id = $company_productid;
        $comment->user_id = $userid;
        $comment->save();
        // add all varibles and save rating
        if($ratec!=0){
            $rate->value = $ratec;
        $rate->connection_id = $company_productid;
        $rate->user_id = $userid;
        $rate->timestamp =strftime("%Y-%m-%d %H:%M:%S", time());
        $rate->save();
        } 
        // return connection id, wich will be used for redirecting user to correct path
        return $company_productid;
                
        
        
    }
    
    // Finds CompanyProduct by id in database. 
    public function find_CompanyProduct($connid){
  
        $companyid = Company_Product::find_by_id($connid)->company_id;
        $productid = Company_Product::find_by_id($connid)->product_id;
        $b  =    Company::find_by_id($companyid);
        $c  =    Product::find_by_id($productid);
        $a = array($b,$c);
        return $a;
    }
    
    // Method finds comments on a specific con_id and orders result depending on $order
    public function commentbyConnId($connid,$order){
       $comment = new Comment();
       if($order==""){
           $order == 0;
       }
       $a = $comment->find_comments_on_Connection($connid,$order);
        
       return $a;
         
    }
    
    //recieves a comment, userid and conid and saves the comment with the id's in the database
    public function commentOnly($commentc="",$userid=0,$connid=0){
            
            if($commentc!="" && $userid!=0 && $connid!=0){
                $comment = new Comment();
                $comment->comment = $commentc;
                $comment->timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
                $comment->connection_id = $connid;
                $comment->user_id = $userid;
                $comment->save();
            }else{
                return "noe er feil.";
            }
        
        
    }
    
    // Searches through database to find CompanyProducts matching the keyword.
    public function searchComPro($kw){
        
        $cp = new Company_Product();
        $res = $cp->searchComPro($kw);
        
        return $res;


    }
    
    // Function grants access to a product by id or name
    public function grantAccessP($userid=0,$email="",$productname="",$productid=0){
        //give access for user to change info on a product
        if($userid==0){
            //user id is not placed
            if($email!=""){
           $login = new Login();
         $userid = $login->existingEmail($email)->userid;
            }else{
                return "Userid eller Email må være med";
            }
        }else{
            //userid is placed all good
        }
        if($productid==0){
            if($productname!=""){
                $product = new Product();
                $productid = $product->productExists($productname)->id;
                
            }else{
                return "Produktnavn eller Produkt id må være med";
            }
        }
        if($productid!=0 && $userid!=0){
           $companyid =0;
            $company_user = new Company_User();
            if(!$company_user->exist($userid, $companyid, $productid)){
                $company_user->user_id = $userid;
            $company_user->product_id = $productid;
            $company_user->company_id = 0;
            $company_user->save();
            }else{
                return "Brukeren har allerede tilgang";
            }
            
        }
        
    }
    
    // Function grants access to a company by id or name
    public function grantAccessC($userid=0,$email="",$companyname="",$companyid=0){
            //give access for user to change info on a company
        if($userid==0){
            //user id is not placed
            if($email!=""){
           $login = new Login();
         $userid = $login->existingEmail($email)->userid;
            }else{
                return "Userid eller Email må være med";
            }
        }else{
            //userid is placed all good
        }
        if($companyid==0){
            if($companyname!=""){
                $company = new Company();
                $companyid = $company->companyExists($companyname)->id;
                
                
            }else{
                return "Bedriftsanvn eller BedriftsID må være med";
            }
        }
        if($companyid!=0 && $userid!=0){
            $company_user = new Company_User();
            $productid = 0;
            echo "  "; 
            echo $userid."  ";
            echo $companyid." ";
            echo $productid."  ";
            
            if(!$company_user->exist($userid, $companyid, $productid)){
           
            $company_user->user_id = $userid;
            $company_user->product_id = 0;
            $company_user->company_id = $companyid;
            $company_user->save();
            
            
            }else{
                return "Brukeren har allerede tilgang";
            }
        }
        
    }
    
    // Finds the products a user has access to edit
    public function findPforEdit($userid){
        $company_user = new Company_User();
        $all = $company_user->findByUserid($userid);
        
        if($all){
        foreach($all as $company_user){
            $a[] = Product::find_by_id($company_user->product_id);;
        }
        return $a;
        }
        else{
            echo "Brukeren har ikke tilgang til noen bedrifter";
        }
    }
    
    // Finds the companies a user has access to edit
    public function findCforEdit($userid){
        
     $company_user = new Company_User();
     $all = $company_user->findByUserid($userid);
     if($all){
        
        $a= array();
        foreach($all as $company_user){
            $a[] = Company::find_by_id($company_user->company_id);
               }
        return $a;   
        
     }
     else{
         
         echo "Brukeren har ikke tilgang til noen produkter";
         
     }
    }
    
    //Method recieves a new description on company and saves it
    public function changeCompanyDesc($companyid,$desc){
        $company= company::find_by_id($companyid);
        $company->description = $desc;
        $company->save();
        
    }
    
    //Method recieves a new description on product and saves it
     public function changeProductDesc($productid,$desc){
        $product= product::find_by_id($productid);
        $product->description = $desc;
        $product->save();
        
    }
    
    // Recieves sorttype and search word and returns a sortet table.
    public function searchHandler($b,$d){
         $ret = ('<table border"1">');
    $ret.= "<tr>";
    if($d==0  || $d == 5 || $d==6 || $d == 7 || $d ==8 ){
         $ret.= ('<th><a href="?sort=1&word='.$b.'">Bedriftsnavn</a></th>');
         $ret.= ('<th><a href="?sort=2&word='.$b.'">Produktnavn</a></th>');
         $ret.= ('<th><a href="?sort=3&word='.$b.'">Karakter</a></th>');
         $ret.= ('<th><a href="?sort=4&word='.$b.'">Visninger</a></th>');
      
   }else{
         $ret.= ('<th><a href="?sort=5&word='.$b.'">Bedriftsnavn</a></th>');
         $ret.= ('<th><a href="?sort=6&word='.$b.'">Produktnavn</a></th>');
         $ret.= ('<th><a href="?sort=7&word='.$b.'">Karakter</a></th>');
         $ret.= ('<th><a href="?sort=8&word='.$b.'">Visninger</a></th>');
   }
   
  
$co = new Company_product();
$c = "";
  $c = $co->search($b,$d);
    if (!$c==null){
       
    $ret.= ('<tr>');
for($i=0;$i<count($c);$i++){
    for($j=0;$j<4;$j++){
        $b= $c[$i][$j];
        $ret.= ("<td><a href='compro.php?id=".$c[$i][4]."'>".$b."</a></td>");
        if($j == 3){
            $ret.= ('</tr>');
        }
    }
  
    }
$ret.= ('</table>'); 
    return $ret;
    }else{
        return "Ingen søkeresultat med det søkeordet";
    }
    }
    
}   

$CP_controller = new CP_Controller();

?>


